package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.CustomException;
import com.itheima.common.R;
import com.itheima.domain.Category;
import com.itheima.domain.Dish;
import com.itheima.domain.DishFlavor;
import com.itheima.dto.DishDto;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    //菜品
    @Autowired
    private DishService dishService;

    //菜品口味
    @Autowired
    private DishFlavorService dishFlavorService;

    //菜品分页查询获得菜品分类需要使用到
    @Autowired
    private CategoryService categoryService;

    //缓存
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 添加新菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){

        log.info("dishDto参数：{}",dishDto);

        //清除所有菜品的缓存数据
        //Set keys = redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);

        //清理某个分类下的菜品缓存数据
        String key = "dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
        redisTemplate.delete(key);

        //判断
        if(null==dishDto)return R.error("菜品参数为空！");
        //调用自定义方法
        dishService.saveWithFlavor(dishDto);


        return R.success("新增菜品成功！");

    }



    /**
     * 菜品分页条件查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "10") int pageSize, String name) {

        //构造分页构造器
        Page<Dish> pageInfo = new Page<Dish>(page,pageSize);

        Page<DishDto> dishDtoPage = new Page<DishDto>();

        //构建条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加具体条件      为false不添加条件
        queryWrapper.like( Optional.ofNullable(name).isPresent() , Dish::getName, name);
        //构造排序条件 sort升序                修改时间降序排
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //调用方法  查询菜品分页对象  此时没有每个菜品对应的分类名称
        dishService.page(pageInfo, queryWrapper);


        //对象拷贝  records单独处理
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        //取出dish集合
        List<Dish> records = pageInfo.getRecords();  //Dish对象集合
        //非空判断
        if(CollectionUtils.isEmpty(records)) throw new CustomException("分页查询数据为空！");

        //Dish  转为  DishDto
        List<DishDto> list = records.stream().map((item) -> {   //item表示集合中每一个dish

            DishDto dishDto = new DishDto();              //空对象
            BeanUtils.copyProperties(item, dishDto);      //对象拷贝

            if(null != item.getCategoryId()) {            //菜品分类id不为null,这种取值判断不占用内存
                /* ====================================================== */
                Long categoryId = item.getCategoryId();   //分类id
                Category category = categoryService.getById(categoryId); //根据id查询分类对象
                if (null != category) {
                    String categoryName = category.getName();
                    dishDto.setCategoryName(categoryName);    //设置名称
                }
                /* ====================================================== */
            }
            //返回
            return dishDto;
           //收集
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list); //DishDto对象集合
        return R.success(dishDtoPage);
    }



    /**
     * 根据id查询菜品及口味  回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable(value="id") Long id){
        log.info("菜品id:{}",id);
        //判断
        if(null==id)throw new CustomException("菜品id为空，查询失败！");

        //自定义方法查询菜品数据及口味
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        //返回
        return R.success(dishDto);

    }


    /*
     * 修改菜品数据
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> updateById(@RequestBody DishDto dishDto){
        log.info("修改的菜品数据:{}",dishDto.toString());

        //判断
        if(null==dishDto) return R.error("修改菜品的传递参数为空！");
        //调用方法
        dishService.updateWithFlavor(dishDto);

        return R.success("菜品修改成功！");
    }



    /*
     * 根据id删除  单删\批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteById(@RequestParam(required=true,value = "ids") List<Long> ids){
         log.info("ids数据:{}",ids);
         //判断
        if(CollectionUtils.isEmpty(ids)) return R.error("id为空，无法删除");

        //调用自定义方法
        dishService.deleteByIds(ids);

        return R.success("菜品删除成功");
    }


    /**
     * 批量起售 或 停售
     * @param status  /{statud}?id=xxxx
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateSta(@PathVariable(required=true,value="status")Integer status,
                               @RequestParam(required=true,value = "ids")Long[] ids){
        //
        //调用自定义方法
        dishService.updateStatus(status,ids);
        return R.success("修改成功");
    }


    /** 添加口味 左边菜品列表 菜品的主id
     *  根据条件 表Dish中 category_id、 status = 1查询菜品分类对应的 菜品数据
     * @param dish       url=xxx?categoryId=xxxx
     *  根据菜品分类id  查询分类下具体的菜
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){

        log.info("菜品分类id:{}",dish.getCategoryId());
        //判断
        if(null==dish.getCategoryId())throw new CustomException("菜品分类id为空");


        List<DishDto> dishDtoList = null;   //为空

        //构造key
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();//dish_xxxxxxxxxxxxx_1

        //先从Redis中获取缓存数据          //缓存中拿数据赋值
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if(null != dishDtoList){
        //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }


        //构造条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //过滤条件
        queryWrapper.eq(null!=dish.getCategoryId(),Dish::getCategoryId,dish.getCategoryId());
        //添加条件 查询状态为 1 (起售状态) 的菜品
        queryWrapper.eq(Dish::getStatus,1);
        //排序
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        //SQL: select * from dish where category_id = ? and status =1
        List<Dish> list = dishService.list(queryWrapper);
        //return R.success(list);
        //判断
        if(CollectionUtils.isEmpty(list))throw new CustomException("当前分类下暂无菜品");

        //菜品所属分类的分类名称处理  和  菜品的口味处理
        dishDtoList = list.stream().map(item -> {
            DishDto dishDto = new DishDto();         //创建空对象
            BeanUtils.copyProperties(item, dishDto);  //对象拷贝

            Long categoryId = item.getCategoryId();  // 获取分类cotegory_id
            Category category = categoryService.getById(categoryId); //根据cotegory_id查询到分类对象
            if (null != category) {                  // 健壮性判断  分类对象不为空
                String name = category.getName();    // 获取分类名称
                dishDto.setCategoryName(name);       // 将名称设置到 categoryName属性上
            }

            Long id = item.getId();  // 获取当前菜品id  菜品表dish
            // 构建条件构造器
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, id);                              //dish_id  = id

            // SQL:select * from dish_flavor  where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);  //当前菜品id查询所有口味
            if(!CollectionUtils.isEmpty(dishFlavorList)){
                dishDto.setFlavors(dishFlavorList);     // 将该口味设置到 flavor属性上
            }
            //返回
            return dishDto;
        }).collect(Collectors.toList());

        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到redis  缓存60分钟
        redisTemplate.opsForValue().set(key,dishDtoList,60,TimeUnit.MINUTES);  //查询结果  存入缓存

        return  R.success(dishDtoList);
    }

}
